#include "serverPool.h"
void *serverFunc(void *arg) {
    serverPool_t *serverPool = (serverPool_t *)arg;
    syslog(LOG_INFO, "工作线程已启动（线程ID：%lu）", (unsigned long)pthread_self());

    while(1) {
        pthread_mutex_lock(&serverPool->mutex);

        // 等待任务或退出信号
        while(serverPool->exitFlag == 0 && serverPool->que.queSize <= 0) {
            pthread_cond_wait(&serverPool->cond, &serverPool->mutex);            
        }

        if(serverPool->exitFlag == 1) {
            syslog(LOG_INFO, "工作线程正在离开（线程ID：%lu）", (unsigned long)pthread_self());
            printf("工人离开了。\n");
            pthread_mutex_unlock(&serverPool->mutex);
            pthread_exit(NULL);
        }

        int netfd = serverPool->que.head->data;
        syslog(LOG_INFO, "正在处理基于 netfd=%d 的连接", netfd);
        printf("我是工人netfd=%d.\n", netfd);

        deQueue(&serverPool->que);
        pthread_mutex_unlock(&serverPool->mutex);

        // 初始化路径处理结构
        path_t path;
        initPath(&path);

        char initpath[] = "/home/gilgamesh/homework/Client";
        path.initialPath = strdup(initpath);  // 使用strdup自动分配内存并复制
        strcpy(path.absolutePath, initpath);
        syslog(LOG_DEBUG, "初始路径设置为:%s", path.absolutePath);

        char retArr[1024] = {0};

        while(1) {
            signalsend_t signal;
            memset(&signal, 0, sizeof(signal));  // 使用标准库函数替代bzero

            int cmd;
            ssize_t stre = recv(netfd, &cmd, sizeof(int), 0);

            if(stre == 0) {
                syslog(LOG_INFO, "关闭连接在%d的连接。", netfd);
                break;
            } else if(stre < 0) {
                syslog(LOG_ERR, "接受%d上的数据出错: %m", netfd);
                break;  // 修复：添加break退出循环
            }

            printf("cmd = %d\n", cmd);

            char buf[1024 * 2] = {0};
            // 接收数据大小
            if(recv(netfd, &signal.size, sizeof(signal.size), 0) <= 0) {
                syslog(LOG_ERR, "接收数据大小失败，连接可能已断开");
                break;
            }
            if(cmd == CD) {
                syslog(LOG_DEBUG, "正在处理CD命令%d", netfd);
                if(recv(netfd, &signal.pathname, sizeof(signal.pathname), 0) <= 0) {
                    syslog(LOG_ERR, "接收CD命令参数失败");
                } else {
                    printf("进入了cd命令\n");
                    if(isTruePath(path, signal)) {
                        cd(&path, signal.pathname, signal.size);
                        syslog(LOG_DEBUG, "CD命令执行成功新路径%s", path.absolutePath);

                        printf("------------\n");
                        printf("abs:%s\n", path.absolutePath);
                        printf("pwd:%s\n", path.pwd);
                    } else {
                        syslog(LOG_WARNING, "CD命令失败，%d上的路径无效。", netfd);
                        printf("CD:地址错误！\n");

                        char errmsg[] = "地址输入错误！";
                        FileBuf_t filebuf;
                        memset(&filebuf, 0, sizeof(filebuf));
                        filebuf.sig_t = CD;
                        filebuf.size = strlen(errmsg);
                        strcpy(filebuf.buf, errmsg);

                        ssize_t sent = send(netfd, &filebuf, sizeof(filebuf), MSG_NOSIGNAL);
                        if(sent < 0) {
                            syslog(LOG_ERR, "在%d上发送CD错误响应时出错: %m", netfd);
                        }
                    }
                }
            } else if(cmd == LS) {
                syslog(LOG_DEBUG, "执行LS命令:%d", netfd);
                if(recv(netfd, &signal.pathname, sizeof(signal.pathname), 0) <= 0) {
                    syslog(LOG_ERR, "接收LS命令参数失败");
                } else if(signal.size != 0) {
                    if(isTruePath(path, signal)) {
                        // 创建临时路径对象
                        path_t temp_path;
                        initPath(&temp_path);
                        temp_path.initialPath = strdup(initpath);
                        strcpy(temp_path.absolutePath, path.absolutePath);

                        // 复制路径栈
                        sNode_t *p = path.pathStack.bottom;
                        while(p != NULL) {
                            pathStackPush(&temp_path.pathStack, p->pathname);
                            p = p->next;
                        }

                        cd(&temp_path, signal.pathname, signal.size);
                        printf("bef == %s\n", temp_path.absolutePath);
                        printf("aft == %s\n", temp_path.absolutePath);

                        ls(temp_path.absolutePath, retArr);

                        FileBuf_t filebuf;
                        memset(&filebuf, 0, sizeof(filebuf));
                        filebuf.sig_t = LS;
                        filebuf.size = strlen(retArr);
                        strcpy(filebuf.buf, retArr);

                        ssize_t sent = send(netfd, &filebuf, sizeof(filebuf), MSG_NOSIGNAL);
                        if(sent < 0) {
                            syslog(LOG_ERR, "在%d上发送LS响应时出错: %m", netfd);
                        } else {
                            syslog(LOG_DEBUG, "LS命令成功执行，发送了%zd bytes.", sent);
                        }

                        freePath(&temp_path);  // 释放临时路径对象
                    } else {
                        syslog(LOG_WARNING, "LS命令失败，%d上的路径无效！", netfd);
                        printf("LS:地址错误！\n");

                        char errmsg[] = "地址输入错误！";
                        FileBuf_t filebuf;
                        memset(&filebuf, 0, sizeof(filebuf));
                        filebuf.sig_t = LS;
                        filebuf.size = strlen(errmsg);
                        strcpy(filebuf.buf, errmsg);

                        ssize_t sent = send(netfd, &filebuf, sizeof(filebuf), MSG_NOSIGNAL);
                        if(sent < 0) {
                            syslog(LOG_ERR, "在%d上发送LS错误响应时出错: %m", netfd);
                        }
                    }
                } else {
                    ls(path.absolutePath, retArr);

                    FileBuf_t filebuf;
                    memset(&filebuf, 0, sizeof(filebuf));
                    filebuf.sig_t = LS;
                    filebuf.size = strlen(retArr);
                    strcpy(filebuf.buf, retArr);

                    ssize_t sent = send(netfd, &filebuf, sizeof(filebuf), MSG_NOSIGNAL);
                    if(sent < 0) {
                        syslog(LOG_ERR, "在%d上发送LS响应时出错: %m", netfd);
                    } else {
                        syslog(LOG_DEBUG, "LS命令成功执行，发送了%zd bytes.", sent);
                    }
                }
            } else if(cmd == PWD) {
                syslog(LOG_DEBUG, "PWD命令正在处理%d", netfd);
                if(recv(netfd, &signal.pathname, sizeof(signal.pathname), 0) <= 0) {
                    syslog(LOG_ERR, "接收PWD命令参数失败");
                } else {
                    pwd(&path, buf);

                    FileBuf_t filebuf;
                    memset(&filebuf, 0, sizeof(filebuf));
                    filebuf.sig_t = PWD;
                    filebuf.size = strlen(buf);
                    strcpy(filebuf.buf, buf);

                    ssize_t sent = send(netfd, &filebuf, sizeof(filebuf), MSG_NOSIGNAL);
                    if(sent < 0) {
                        syslog(LOG_ERR, "在%d上发送PWD响应时出错: %m", netfd);
                    } else {
                        syslog(LOG_DEBUG, "PWD执行成功当前路径：%s", path.absolutePath);
                    }
                }
            } else if(cmd == REMOVE) {
                printf("***************\n");
                if(recv(netfd, signal.pathname, sizeof(signal.pathname), MSG_WAITALL) <= 0) {
                    syslog(LOG_ERR, "接收REMOVE命令参数失败");
                } else {
                    // 创建临时路径对象
                    path_t rm_path;
                    initPath(&rm_path);
                    rm_path.initialPath = strdup(initpath);
                    strcpy(rm_path.absolutePath, path.absolutePath);

                    // 复制路径栈
                    sNode_t *p_rm = path.pathStack.bottom;
                    while(p_rm != NULL) {
                        pathStackPush(&rm_path.pathStack, p_rm->pathname);
                        p_rm = p_rm->next;
                    }

                    cd(&rm_path, signal.pathname, signal.size);
                    printf(" == %s\n", rm_path.absolutePath);

                    if(remove(rm_path.absolutePath) == 0) {
                        printf("文件删除成功！\n");
                    } else {
                        printf("文件删除失败！\n");
                        syslog(LOG_ERR, "删除文件失败: %m");
                    }

                    freePath(&rm_path);  // 释放临时路径对象
                }
            } else if(cmd == MKDIR) {
                printf("***************\n");
                if(recv(netfd, signal.pathname, sizeof(signal.pathname), MSG_WAITALL) <= 0) {
                    syslog(LOG_ERR, "接收MKDIR命令参数失败");
                } else {
                    // 创建临时路径对象
                    path_t mk_path;
                    initPath(&mk_path);
                    mk_path.initialPath = strdup(initpath);
                    strcpy(mk_path.absolutePath, path.absolutePath);

                    // 复制路径栈
                    sNode_t *p_mk = path.pathStack.bottom;
                    while(p_mk != NULL) {
                        pathStackPush(&mk_path.pathStack, p_mk->pathname);
                        p_mk = p_mk->next;
                    }

                    cd(&mk_path, signal.pathname, signal.size);
                    printf(" == %s\n", mk_path.absolutePath);

                    if(mkdir(mk_path.absolutePath, 0775) == 0) {
                        printf("成功！\n");
                    } else {
                        printf("失败！\n");
                        syslog(LOG_ERR, "创建目录失败: %m");
                    }

                    freePath(&mk_path);  // 释放临时路径对象
                }
            } else if(cmd == RMDIR) {
                printf("***************\n");
                if(recv(netfd, signal.pathname, sizeof(signal.pathname), MSG_WAITALL) <= 0) {
                    syslog(LOG_ERR, "接收RMDIR命令参数失败");
                } else {
                    // 创建临时路径对象
                    path_t rd_path;
                    initPath(&rd_path);
                    rd_path.initialPath = strdup(initpath);
                    strcpy(rd_path.absolutePath, path.absolutePath);

                    // 复制路径栈
                    sNode_t *p_rd = path.pathStack.bottom;
                    while(p_rd != NULL) {
                        pathStackPush(&rd_path.pathStack, p_rd->pathname);
                        p_rd = p_rd->next;
                    }

                    cd(&rd_path, signal.pathname, signal.size);
                    printf(" == %s\n", rd_path.absolutePath);

                    if(rmdir(rd_path.absolutePath) == 0) {
                        printf("删除成功！\n");
                    } else {
                        printf("删除失败！\n");
                        syslog(LOG_ERR, "删除目录失败: %m");
                    }

                    freePath(&rd_path);  // 释放临时路径对象
                }
            } else if(cmd == PUTS) {
                char filename[1024];
                memset(filename, 0, sizeof(filename));
                strcpy(filename, path.absolutePath);
                strcat(filename, "/");

                printf("++++++++++++++++filename = %s\n", filename);

                if(recv(netfd, buf, signal.size, 0) <= 0) {
                    syslog(LOG_ERR, "接收PUTS命令文件名失败");
                } else {
                    printf("buf = %s\n", buf);
                    strcat(filename, buf);

                    printf("----------------size=%d\n", signal.size);
                    printf("----------------filename = %s\n", filename);

                    printf("puts函数before\n");
                    put_s(netfd, filename);
                }
            } else if(cmd == GETS) {
                char getsFileName[1024];

                if(recv(netfd, buf, signal.size, MSG_WAITALL) <= 0) {
                    syslog(LOG_ERR, "接收GETS命令文件名失败");
                } else {
                    printf("filename=%s,size=%d\n", buf, signal.size);

                    strcpy(getsFileName, path.absolutePath);
                    strcat(getsFileName, "/");
                    strcat(getsFileName, buf);

                    get_s(netfd, getsFileName);
                }
            } else {
                syslog(LOG_WARNING, "未知命令: %d", cmd);
            }

        }

        freePath(&path);  
        close(netfd);
        return (void*)0;  
    }
}

int makeWorker(serverPool_t *serverPool) {
    for(int i = 0; i < serverPool->tidArr.workerNum; i++) {
        if(pthread_create(&serverPool->tidArr.id[i], NULL, serverFunc, serverPool) != 0) {
            syslog(LOG_ERR, "创建工作线程 #%d 失败", i+1);
            return -1;  // 添加错误处理
        }
        printf("成功创建工作线程 #%d, 线程ID: %lu\n", i+1, (unsigned long)serverPool->tidArr.id[i]);
    }
    return 0;
}
